#include <board.h>
#include <errno.h>

#ifdef SEGGER_RTT
#include "segger_rtt.c"
#endif

int _write(int file, char *ptr, int len) {
    int DataIdx;
    for (DataIdx = 0; DataIdx < len; DataIdx++) {
        __io_putchar(*ptr++);
    }
    return len;
}

int _read(int file, char *ptr, int len) {
    int DataIdx;

    for (DataIdx = 0; DataIdx < len; DataIdx++) {
        *ptr++ = __io_getchar();
    }

    return len;
}

/* ------------------------------------------------------------------------- */
/*!Increase program data space
   This is a minimal implementation.  Assuming the heap is growing upwards
   from __heap_start towards __heap_end.
   See linker file for definition.
   @param[in] incr  The number of bytes to increment the stack by.
   @return  A pointer to the start of the new block of memory                */
/* ------------------------------------------------------------------------- */
void *_sbrk(int incr) {
    extern int HEAP_BASE; // set by linker
    extern int HEAP_END;  // set by linker

    static char *heap_end; /* Previous end of heap or 0 if none */
    char *prev_heap_end;

    if (0 == heap_end) {
        heap_end = (char *)(&HEAP_BASE); /* Initialize first time round */
    }

    prev_heap_end = heap_end;
    heap_end += incr;
    // check
    if (heap_end >= (char *)(&HEAP_END)) {
        errno = ENOMEM;
        return (char *)-1;
    }
    return (void *)prev_heap_end;
} /* _sbrk () */

